<?php
declare (strict_types=1);

namespace app\controller\adminapi\user;

use app\common\model\system\Menu;
use app\common\services\table\DataForm;
use app\common\services\table\DataTable;
use hiduoke\controller\AdminController;
use hiduoke\services\FormBuilder;

/**
 * Notes: 用户组管理
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/8/6 03:50
 */
class Group extends AdminController
{
    /**
     * @var \app\common\model\user\UserGroup
     */
    public $model;

    public function initialize()
    {
        $this->model = new \app\common\model\user\UserGroup();
    }


    // 新版本用户列表
    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $column = $DataTable
            ->setFilterFields(['menu_ids','half_menu_ids','type', 'level','rules'])
            ->setField('status', ['render' => 'switch'])
            ->setHideFields(['update_time', 'create_time', 'join_ip'])
            ->operation()->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }


    /**
     * 获取表单
     * @param $id
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function form()
    {
        $dataForm = new DataForm($this->model);
        $form = $dataForm
            ->setFilterFields(['half_menu_ids', 'rules','type','level'])
            ->setField('status', ['render' => 'switch'])
            ->setRule('menu_ids', FormBuilder::dkMenuTree('menu_ids', '规则', $dataForm->row['menu_ids'] ?? []))
            ->create();
        return $this->success('', $form);
    }


    public function getOption()
    {
        $data = [];
        $list = (new Menu())->where([])->order("sort asc")->select()->toArray();
        foreach ($list as $value) {
            $option = array(
                "label"     => $value['menu_name'],
                "pid"       => $value["pid"],
                "value"     => $value["id"],
                "id"        => $value['id'],
                'menu_type' => $value['menu_type'],
                'is_show'   => $value['is_show']
            );
            $data[$value['id']] = $option;
        }
        return get_tree_children($data);
    }
}
